import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

/// 获取文件路径
/// 1. 查找一个本地路径
/// 2. 创建一个文件路径的引用
/// 3. 向文件中写数据
/// 4. 从文件中读数据

class FileApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String appTitle = 'File Demo';
    return MaterialApp(
      title: appTitle,
      theme: ThemeData(primarySwatch: Colors.red),
      home: FileAppPage(
        title: appTitle,
        storage: Storage(),
      ),
    );
  }
}

class FileAppPage extends StatefulWidget {
  final String title;
  final Storage storage;

  FileAppPage({Key key, this.title, this.storage}) : super(key: key);

  @override
  State<StatefulWidget> createState() => FileAppPageState();
}

class FileAppPageState extends State<FileAppPage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    widget.storage.readCounter().then((int value) {
      setState(() {
        _counter = value;
      });
    });
  }

  Future<File> _incrementCounter() async {
    setState(() {
      _counter++;
    });
    return widget.storage.writeCounter(_counter);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('Button tapped $_counter time${_counter <= 1 ? '' : 's'}'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Storage {
  /// 获取本地路径
  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);
    return directory.path;
  }

  /// 获取文件路径
  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
  }

  /// 读取文件内容
  Future<int> readCounter() async {
    try {
      final file = await _localFile;
      // 读取文件
      String content = await file.readAsString();
      return int.parse(content);
    } catch (e) {
      return 0;
    }
  }

  // 写文件
  Future<File> writeCounter(int counter) async {
    final file = await _localFile;
    return file.writeAsString('$counter');
  }
}
